<%@ include file="/common/taglibs.jsp"%>
<%@ page language="java" pageEncoding="UTF-8"%>
<head>
	<title>工程文档管理</title>
	<meta name="menu" content="systemMenu" />
	<meta name="nav" content="0" />
<%@ include file="/common/extjs.jsp"%>

	<script type="text/javascript" src="${ctx}/ext/plugin/Ext.ux.form.FileUploadField.js" charset="utf-8"></script>
		
	<script type="text/javascript">
	
		var thisfilePath;
		var  editData ={};
		if(Ext.form.DateField){
	   Ext.apply(Ext.form.DateField.prototype, {
	      disabledDaysText  : "禁用",
	      disabledDatesText : "禁用",
	      minText           : "该输入项的日期必须在 {0} 之后",
	      maxText           : "该输入项的日期必须在 {0} 之前",
	      invalidText       : "{0} 是无效的日期 - 必须符合格式： {1}",
	      format            : "Y年m月d日",
	      setValue : function(date){
	        return Ext.form.DateField.superclass.setValue.call(this, this.formatDate(this.parseDate(date)));
	    }
	   });
}
Ext.onReady(function(){
Ext.form.Field.prototype.msgTarget = 'under';
Ext.state.Manager.setProvider(new Ext.state.CookieProvider());
Ext.QuickTips.init();
var fm = Ext.form;
    var expander = new Ext.grid.RowExpander({
    	expand:true,
        tpl : new Ext.Template(
            "<p><b>资料下载:</b><a href='/"+appConfig.appName+"/servlet/fileDownload?id={id}'>{fileName}</a></p>",
            "<p>"
        )
    });
var cm = new Ext.grid.ColumnModel({
							
							columns:[
							expander,
   							 {
					           header:  	'图片种类',
					           dataIndex: 'type',
					           width: 		100
     					   },
   							 {
					           header:  	'文件名称',
					           dataIndex: 'fileName',
					           width: 		100
     					   },
   							 {
					           header:  	'图片拍摄时间',
					           dataIndex: 'fileTime',
					           width: 		100
     					   },
   							 {
					           header:  	'文件实际名称',
					           dataIndex: 'path',
					           width: 		100
     					   },
   							 {
					           header:  	'上传用户',
					           dataIndex: 'uploadPerson',
					           width: 		100
     					   },
   							 {
					           header:  	'上传时间',
					           dataIndex: 'uploadTime',
					           width: 		100
     					   },
   							 {
					           header:  	'备注',
					           dataIndex: 'remark',
					           width: 		100
     					   },{
           					 id:'id',
					           header: 		'序号',
					           dataIndex: 'id',
					           hidden: 		true,
					           width: 		10
        				 }
   					 ],
   					 defaults:{
   					 	renderer:Jinyi.project.Format.textAreaRenderer
   					 }
   					 });
   	cm.defaultSortable = true;
	   // Record
    AppAttachment = Ext.data.Record.create([
    						{name: 'id', type: 'string'},
							{name: 'fullPath', type: 'string'},	
							{name: 'path', type: 'string'},
							{name: 'type', type: 'string'},
							{name: 'uploadPerson', type: 'string'},	
							{name: 'tableId', type: 'string'},
							{name: 'partId', type: 'string'},
							{name: 'tableName', type: 'string'},
							{name: 'tableField', type: 'string'},	
							{name: 'uploadTime', type: 'string'},
							{name: 'fileName', type: 'string'},
							{name: 'fileTime', type: 'string'},
							{name: 'fileNo', type: 'string'},	
							{name: 'status', type: 'string'},
            				{name: 'remark', type: 'string'}
      ]);

    // create the Data Store
var store = new Ext.data.Store({
        			url: "/"+appConfig.appName+"/api/attachments.html",
							baseParams :{
				 			method: 'searchExt',
				 			tableId:'${param.tableId}',
				 			partId:'${param.partId}',
							tableName:'${param.tableName}',
				 			tableField:'${param.tableField}'
					},
        reader: new Ext.data.JsonReader({
        		totalProperty: 'totalCounts',
             	root: 'results',
             	id: 'id'
           }, AppAttachment),	   
        listeners:{
	    				load :function (){
	    				Ext.getCmp("editgrid").getSelectionModel().selectFirstRow();
	    		 }
	    	},
        sortInfo:{field:'id', direction:'ASC'}
    });
var viewport = new Ext.Viewport({
        layout:'border',
        items:[{
        xtype: 'grid',
        tbar : [{text: '新增',iconCls : 'dt_add',handler:addOneData},
	 		    		'->',
    		   	{text:'刷新',iconCls:'dt_flush',handler:reloadData}],
        
        id:'editgrid',
        enableColumnHide :false,
        loadMask :{
         msg :'正在加载....'
        },
      	region:'center',
      	minSize: 200,
		width: 500,
	    plugins: [expander],
	    autoScroll :true,
       	store: store,
        cm: cm,      
        sm: new Ext.grid.RowSelectionModel({
                singleSelect: true,
                listeners: {
                    rowselect: function(sm, row, rec) {
                    		Ext.getCmp("saveBt").enable();
                    		Ext.getCmp("deleteBt").enable();
                    	var form =Ext.getCmp("editform").getForm();
                        form.loadRecord(rec);
                    }
                }
            }),
        border: true,
	      listeners: {
	        	render: function(g) {
	        	 var form =Ext.getCmp("editform").getForm();
	        	    form.reset();
	        	 	   reloadData();
	        	},
	        	delay: 10
       		},
        autoExpandColumn: 'id'
        }, {
        xtype: 'form',
        id: 'editform',
        fileUpload: true,
        region:'east',
        tbar : [{text: '新增',iconCls : 'dt_add',handler:addOneData},
        		{text: '上传文件',id:"saveBt",disabled :true,iconCls : 'dt_save',handler:saveOneData},
        		{text : '删除',id:"deleteBt",disabled :true,iconCls : 'dt_del',handler:deleteOneData}
	 		    ],
        split :true,
        frame: true,
        collapsible :true,
        collapseMode:'mini',
        autoScroll :true,
        labelAlign: 'left',
        bodyStyle:'padding:5px',
		width: 285,
        minSize: 280,
        maxSize: 500,
        items: [{
            labelWidth: 80,
            defaults: {width: 140},
            defaultType: 'textfield',
            autoHeight: true,
            bodyStyle: Ext.isIE ? 'padding:0 0 5px 5px;' : 'padding:5px 5px;',
            border: true,
            layout: 'form',
            items: [    
						   {
     					   	   xtype :	'hidden',
					           name: 					'tableId'
     					   },{
     					   	   xtype :	'hidden',
					           name: 					'partId'
     					   },{
     					   	   xtype :	'hidden',
					           name: 					'tableName'
     					   },{
     					   	   xtype :	'hidden',
					           name: 					'tableField'
     					   },{
					            fieldLabel:  	'图片种类',
					            xtype:'combo',
					            typeAhead: true,
							    triggerAction: 'all',
							    lazyRender:true,
							    mode: 'local',
							    listeners :{
							     change :function(field,newvalue,oldValue){
							      var form = Ext.getCmp("editform").getForm();
							       var record = field.findRecord(field.valueField, newvalue);
       				 			   var v = record ? record.get(field.valueField) : field.valueNotFoundText;
							      form.findField('tableField').setValue(v);
							     }
							    
							    },
							    store: new Ext.data.ArrayStore({
							        id: 0,
							        fields: [
							            'value',
							            'text'
							        ],
							        data: getFieldData()
							    }),
							    valueField: 'value',
							    displayField: 'text',
							    allowBlank : false,
					            name: 		  'type'
     					   },{
					            xtype: 'fileuploadfield',
					            id: 'form-file',
					            emptyText: '请选择附件',
					            fieldLabel: '附件上传',
					            name: 'filepath',
					            validator :function (value){
					            
					              var editForm = Ext.getCmp("editform").getForm();
					             
					              var id = editForm.findField("id").getValue();
					            	if (Ext.isEmpty(id) && Ext.isEmpty(value)) {
									   return "请选择一个需要上传的文件";
									} 
									if (!Ext.isEmpty(id) && !Ext.isEmpty(value)) {
									   return "请先新增然后选择要上传的文件";
									}
									if (!Ext.isEmpty(id) && Ext.isEmpty(value)) {
									   return true;
									}
									 var fileExtName = value.toLowerCase();
									if ((fileExtName.indexOf(".jpg") == -1) && (fileExtName.indexOf(".jpeg") == -1) &&(fileExtName.indexOf(".png") == -1) &&(fileExtName.indexOf(".gif") == -1)&&(fileExtName.indexOf(".bmp") == -1)) {
											return "只能上传图片格式的文件";
										} 
									if (Ext.isEmpty(id) && !Ext.isEmpty(value)) {
									 var savebt = Ext.getCmp("saveBt");
									  if(savebt.disabled) {
									  savebt.enable();
									  editForm.findField("tableId").setValue('${param.tableId}');
									  editForm.findField("partId").setValue('${param.partId}');
								  	  editForm.findField("tableName").setValue('${param.tableName}');
									  //editForm.findField("tableField").setValue('${param.tableField}');
									  }
									  var fileName = fileExtName.substring(fileExtName.lastIndexOf('\\')+1,fileExtName.lastIndexOf('.'));
									  editForm.findField("fileName").setValue(fileName);
									} 
									 return true;
					            },
					            buttonText: '',
					            buttonCfg: {
					                iconCls: 'upload-icon'
					            }
					        },{
					           fieldLabel:  	'文件名称',
							    allowBlank : false,
					           name: 					'fileName'
     					   },{
					           fieldLabel:  	'拍摄时间',
					           xtype:			'datefield',
					           name: 					'fileTime'
     					   },{
				   	   		   xtype :	'hidden',
					           name: 					'uploadPerson'
     					   },{
    			   	   		   xtype :	'hidden',
					           name: 					'uploadTime'
     					   },{
     					   	   fieldLabel:  	'备注',
     					   	   xtype :	'textarea',
		                       name: 	'remark'
		                    },{
     					   	   xtype :	'hidden',
					           name: 					'path'
     					   },{
     					   	   xtype :	'hidden',
					           name: 					'fullPath'
     					   },{
     					   	   xtype :	'hidden',
					           name: 					'status'
     					   },{
     					   	   xtype :	'hidden',
			                     name:  	'id'
		                    },{xtype :	'panel',anchor:'95%',
             html: '<font color="red">注: 请先点击新增进行图片上传( 支持 .jpg .jpeg .gif .png .bmp), 图片大小不能大于200K,亦不能小于50K,具体要求请参见市局文件.</font>'}]
            }],
            layout: 'form'
    		}]

});  
 	 function resetForm() {
   	 Ext.getCmp("editform").getForm().reset();               	
	 Ext.getCmp("saveBt").disable();
     Ext.getCmp("deleteBt").disable();      
}
 /**
刷新纪录
*/
function reloadData(){
   	resetForm();
	store.load({});
} 	 
/**
 * 增加一条默认记录
 */ 
function addOneData() {
	  var editfrom =Ext.getCmp("editform");
	  // 展开右边栏
	  	editfrom.expand();
 		Ext.getCmp("saveBt").enable();
	  var form =Ext.getCmp("editform").getForm();
	  form.reset();
	  // 设置隐藏值
	  form.findField("tableId").setValue('${param.tableId}');
	  form.findField("partId").setValue('${param.partId}');
  	  form.findField("tableName").setValue('${param.tableName}');
	  form.findField("tableField").setValue('${param.tableField}');
	  	  	  	  
 }
/**
 * 删除一条记录
 */
function deleteOneData(){
  var editForm = Ext.getCmp("editform").getForm();
	var dataId =  editForm.findField("id").getValue();
    Ext.Msg.confirm('删除操作', '删除将无法恢复,是否继续?', function(btn, text){
 	if (btn == 'yes'){   
	   	// 数据库操作
	   	Ext.Ajax.request({
  	    url: "/"+appConfig.appName+"/api/saveAttachment.html",
        params:{
         	id: dataId,
         	method: 'delete',
    		mode:'json'
        },
        success: function(response, options){
        	 try {
					var responseData = Ext.decode(response.responseText);
           			if (responseData.success == true) {
					 	 reloadData();
           	    	 Ext.example.msg('信息', '数据删除成功！');  
            		 } else { Ext.example.msg('提示', '删除失败！');}
            } catch (e) { Ext.example.msg('提示', '删除失败！请稍后再尝试');}
        },
        failure: function(response, options){Ext.example.msg('警告!', '服务端发生错误,数据删除失败!');}
    }); 
  }
		}); 			 
 }
/**
 * 保存一条数据
 */
function saveOneData(obj){
   var editForm = Ext.getCmp("editform").getForm();
   					//alert(Ext.util.JSON.encode(editForm.getValues()));
          	 if(editForm.isValid()){
	            	 obj.disable();
	           
	            	 editForm.submit({url: "/"+appConfig.appName+"/servlet/imageUpload",
	            		    waitTitle: '上传附件',
	            		    waitMsg: '附件上传中...',
				            method: 'POST',  
				            success: function(form,action){
		  						   	Ext.example.msg('信息', '文件上传成功！'); 
								     reloadData();
					             	obj.enable();
				            },  
				            failure:function(form,action) {  
				                  Ext.example.msg("提示!","文件上传失败!,可能文件过大,图片大小请勿大于200K");  
				 	                obj.enable();               
				            }
	        			});  
        		}
}   
});

</script>
</head>
<body>
</body>
